package com.jia.acl.service.impl;

import com.jia.acl.entity.Permission;
import com.jia.acl.entity.User;
import com.jia.acl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class MemberDetailsService implements UserDetailsService {

    @Autowired
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //System.out.println("=============自定义登录逻辑============");
        User user = userService.selectByUsername(username);
        if (user == null){
            throw new UsernameNotFoundException("没有该用户");
        }
        //System.out.println("user-------"+user);
        List<Permission> permissionList = userService.selectPermissionByUsername(username);
        //System.out.println("permissionList-------"+permissionList);
        List<GrantedAuthority> authorities = new ArrayList<>();

        permissionList.forEach(permission -> {
            String value = permission.getValue();
            if (!StringUtils.isEmpty(value)){
                authorities.add(new SimpleGrantedAuthority(value));
            }
        });
        //System.out.println("authorities----"+authorities);
        user.setAuthorities(authorities);
        //System.out.println("user-------"+user);
        return user;
    }
}
